package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pojo.Role;
import com.pojo.User;
import com.service.IUserService;
import com.shiro.ShiroOperate;
import com.util.AuthImgUtils;
import com.util.EndecryptUtils;
import com.util.FileOperateUtil;
import com.util.Message;
import com.util.Updateself;
import com.util.UserValidate;

@Controller
public class UserController {

	@Resource
	private IUserService userService;
	@Resource
	private User user;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Message login(@RequestBody UserValidate userValidate) {

		UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());
		token.setRememberMe(userValidate.getRememberme());
		return ShiroOperate.authentication(token, userValidate.getCode());
	}

	@RequestMapping(value = "/allUsers", method = RequestMethod.POST)
	@ResponseBody
	public Message getusers(@RequestBody Message message) {
		List<User> list = userService.getallusers(Integer.valueOf(message.getMessage()), message.getGroups());
		// 重新获取总数，保证数据事实刷新
		int count = userService.getCounts();
		Message mess = new Message();
		mess.setUser(list);
		mess.setMessage((int) Math.ceil((float) count / message.getGroups()) + "");
		return mess;
	}

	// 获取总页数
	@RequestMapping(value = "/getCounts", method = RequestMethod.POST)
	@ResponseBody
	public Message getcounts(@RequestBody Message message) {
		// 获取总数
		int count = userService.getCounts();
		Message mess = new Message();
		mess.setMessage((int) Math.ceil((float) count / message.getGroups()) + "");
		return mess;
	}

	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody
	public User adduser(@RequestBody User u) {
		User user = userService.createUser(u);
		int uid = user.getId();
		Set<Role> roles = null;
		if (user.getRole() != null) {
			roles = user.getRole();
			for (Role role : roles) {
				if (role != null) {
					int rid = role.getId();
					userService.correlationRoles(uid, rid);
				}
			}

		}
		return user;
	}

	@RequestMapping(value = "/updateUser/{uid}", method = RequestMethod.PUT)
	@ResponseBody
	public User updateuser(@PathVariable int uid, @RequestBody User u) {
		User user = userService.updateuser(u);
		if (u.getRole() != null && u.getRole().size() != 0) {
			userService.deleteuserroles(uid);
			Set<Role> roles = u.getRole();
			for (Role role : roles) {
				if (role != null) {
					int rid = role.getId();
					userService.correlationRoles(uid, rid);
				}
			}
		}

		return user;
	}

	@RequestMapping(value = "/getUser/{uid}", method = RequestMethod.GET)
	@ResponseBody
	public User getuser(@PathVariable int uid) {
		User user = userService.getUser(uid);
		return user;
	}

	@RequestMapping(value = "/deleteUser/{uid}", method = RequestMethod.DELETE)
	@ResponseBody
	public Message deleteuser(@PathVariable int uid) throws UnauthorizedException {
		try {
			userService.deleteuserroles(uid);
			userService.deleteuser(uid);
			return new Message("delete success");
		} catch (Exception e) {
			e.printStackTrace();
			return new Message("delete failed");
		}
	}

	// 获取验证码
	@RequestMapping(value = "/getAuthImg", method = RequestMethod.GET)
	@ResponseBody
	public void getAuthImg(HttpServletResponse response) throws IOException {
		new AuthImgUtils().service(response);
	}

	@RequestMapping(value = "/getUserByName/{username}", method = RequestMethod.GET)
	@ResponseBody
	public User getUserByName(@PathVariable String username) throws IOException {
		User user = userService.findByUsername(username);
		return user;
	}

	// 锁屏认证
	@RequestMapping(value = "/relogin", method = RequestMethod.POST)
	@ResponseBody
	public Message relogin(@RequestBody UserValidate userValidate) {
		UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());
		return ShiroOperate.authentication(token, null);
	}

	// 锁屏时，取消 登入
	@RequestMapping(value = "/lockout", method = RequestMethod.GET)
	@ResponseBody
	public void logout() {
		ShiroOperate.logout();
	}

	@RequestMapping(value = "/updatepwd", method = RequestMethod.POST)
	@ResponseBody
	public Message updatepwd(@RequestBody UserValidate userValidate) throws IOException {
		UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());
		Message message = ShiroOperate.authentication(token, null);
		if (message.getMessage().equals("login success")) {
			User user = new User();
			user.setName(userValidate.getUsername());
			// 新密码存放在code中
			user.setPassword(userValidate.getCode());
			user = EndecryptUtils.md5Password(user);
			userService.updatepwd(user);
		}
		;

		return message;
	}

	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public Message uploadImg(HttpServletRequest request) throws Exception {
		// 返回上传文件的名称
		List<Map<String, Object>> result = FileOperateUtil.upload(request);
		String temp = (String) result.get(0).get("storeName");
		temp = temp.substring(temp.indexOf("uploadDir"));

		return new Message(temp);
	}

	@RequestMapping(value = "/updateself", method = RequestMethod.POST)
	@ResponseBody
	public Message updateself(@RequestBody Updateself updateself, HttpServletRequest request) throws Exception {
		userService.updateself(updateself);
		// 将之前的头像删除
		Cookie[] cookies = request.getCookies();
		String userName = userService.getCookie(cookies, "userName");
		String img = userService.findByUsername(userName).getImg();
		if (!img.equals("images/ali.gif")) {
			new File(request.getSession().getServletContext().getRealPath("/") + img).delete();
		}
		return new Message("success");
	}
}
